package app;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;


public class DiffDir {

    private File dir;
    private File dir2;

    public DiffDir(File dir, File dir2) {
        this.dir = dir;
        this.dir2 = dir2;
    }

    private void compare() {
        compare(this.dir, this.dir2);
    }

    private void compare(File dir, File dir2) {

        Set<String> compared = new HashSet<>();

        for (String fileName : dir.list()) {
            compared.add(fileName);

            File file1 = new File(dir, fileName);
            File file2 = new File(dir2, fileName);

            if (file2.exists()) {
                compareExist(file1, file2);
            } else {
                System.out.println(file1 + "(存在), " + file2 + "(不存在)");
            }
        }

        for (String fileName : dir2.list()) {
            if (compared.contains(fileName)) {
                continue;
            }

            File file1 = new File(dir, fileName);
            File file2 = new File(dir2, fileName);

            if (file1.exists()) {
                compareExist(file1, file2);
            } else {
                System.out.println(file1 + "(不存在), " + file2 + "(存在)");
            }
        }
    }

    private void compareExist(File file1, File file2) {
        if (file1.isFile()
                && file2.isFile()) {
            compareExistFile(file1, file2);
        } else if (file1.isDirectory()
                && file2.isDirectory()) {
            compareExistDir(file1, file2);
        } else {
            System.out.println(file1.getAbsolutePath() + " 和 " + file2.getAbsolutePath() + " 类型不一样");
        }
    }

    private void compareExistDir(File file1, File file2) {
        compare(file1, file2);
    }

    private void compareExistFile(File file1, File file2) {
        try {
            if (!Arrays.equals(
                    FileUtils.readFileToByteArray(file1),
                    FileUtils.readFileToByteArray(file2))
                    ) {
                System.out.println(file1.getAbsolutePath() + " 和 " + file2.getAbsolutePath() + " 文件内容不一样");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        new DiffDir(new File("D:\\temp\\dir"), new File("D:\\temp\\dir2")).compare();
    }

}